//
//  PhotoCollectionViewController.swift
//  googlypuff
//
//  Created by Open on 2/4/15.
//  Copyright (c) 2015 open-groupe. All rights reserved.
//

import UIKit

private let CellImageViewTag = 3
private let BackgroundImageOpacity: CGFloat = 0.1

class PhotoCollectionViewController: UICollectionViewController {

    var library: ALAssetsLibrary!
    private var popController: UIPopoverController!
    
    private var contentUpdateObserver: NSObjectProtocol!
    private var addedContentObserver: NSObjectProtocol!
    
    //MARK: - lifeCycle
    override func viewDidLoad() {
        super.viewDidLoad()
        library = ALAssetsLibrary()
        
        let backgroundImageView = UIImageView(image: UIImage(named: "background"))
        backgroundImageView.alpha = BackgroundImageOpacity
        backgroundImageView.contentMode = .Center
        collectionView?.backgroundView = backgroundImageView
        
        contentUpdateObserver = NSNotificationCenter.defaultCenter().addObserverForName(PhotoManagerContentUpdateNotification, object: nil, queue: NSOperationQueue.mainQueue(), usingBlock: {
            notification in
            self.contentChangeNotification(notification)
        })
        
        addedContentObserver = NSNotificationCenter.defaultCenter().addObserverForName(PhotoManagerAddedContentNotification, object: nil, queue: NSOperationQueue.mainQueue()){
            notification in
            self.contentChangeNotification(notification)
        }
    }
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        showOrHideNavPrompt()
    }
    deinit {
        let nc = NSNotificationCenter.defaultCenter()
        if contentUpdateObserver != nil {
            nc.removeObserver(contentUpdateObserver)
        }
        if addedContentObserver != nil
        {
            nc.removeObserver((addedContentObserver))
        }
    }
    
}

//MARK: -UICollectionViewDataSource
private let PhotoCollectionCellID = "photoCell"
extension PhotoCollectionViewController : UICollectionViewDataSource
{
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return PhotoManager.sharedManager.photos.count
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PhotoCollectionCellID, forIndexPath: indexPath) as UICollectionViewCell
        let imageView = cell.viewWithTag(CellImageViewTag) as UIImageView
        let photosAssets = PhotoManager.sharedManager.photos
        let photo = photosAssets[indexPath.row]
        
        switch photo.status {
        case .GoodToGo:
            imageView.image = photo.thumbnail
        case .Failed:
            imageView.image = UIImage(named: "photoDownloadError")
        case .Downloading:
            imageView.image = UIImage(named: "photoDownloading")
        }
        return cell
    }
}

// MARK: - UICollectionViewDelegate

extension PhotoCollectionViewController: UICollectionViewDelegate
{
    override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let photos = PhotoManager.sharedManager.photos
        let photo = photos[indexPath.row]
        
        switch photo.status
        {
        case .GoodToGo:
            let detailController =
            storyboard!.instantiateViewControllerWithIdentifier("PhotoDetailViewController") as PhotoDetailViewController
            detailController.image = photo.image
            navigationController?.pushViewController(detailController, animated: true)
        case .Downloading:
            let alert = UIAlertController(title: "Downloading", message: "the image is current downloading", preferredStyle: .Alert)
            alert.addAction(UIAlertAction(title: "ok", style: .Cancel, handler: nil))
            presentViewController(alert, animated: true, completion: nil)
        case .Failed:
            let alert = UIAlertController(title: "Image Failed", message: "The image failed to be create", preferredStyle: .Alert)
            alert.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil))
            presentViewController(alert, animated: true, completion: nil)
        }
    }
}

extension PhotoCollectionViewController: ELCImagePickerControllerDelegate
{
      func elcImagePickerController(picker: ELCImagePickerController!, didFinishPickingMediaWithInfo info: [AnyObject]!) {
        for dictionary in info as [NSDictionary] {
            library.assetForURL(dictionary[UIImagePickerControllerReferenceURL] as NSURL, resultBlock: {
                asset in
                let photo = AssetPhoto(asset: asset)
                PhotoManager.sharedManager.addPhoto(photo)
                },
                failureBlock: {
                    error in
                    let alert = UIAlertController(title: "Permission Denied", message: "To Access your photos, please change the premissions in Setting", preferredStyle: .Alert)
                    alert.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil))
                    self.presentViewController(alert, animated:true, completion: nil)
            })
        }
        if Utils.userInterfaceIdiomIsPad
        {
            popController?.dismissPopoverAnimated(true)
        }else {
            dismissViewControllerAnimated(true, completion: nil)
        }
    }
    
    func  elcImagePickerControllerDidCancel(picker: ELCImagePickerController!) {
        if Utils.userInterfaceIdiomIsPad {
            popController?.dismissPopoverAnimated(true)
        }else {
            dismissViewControllerAnimated(true, completion: nil)
        }
    }
}

extension PhotoCollectionViewController {
    @IBAction func addPhotoAssets(sender: AnyObject!){
        if popController?.popoverVisible == true {
            popController.dismissPopoverAnimated(true)
            popController = nil
            return
        }
        
        let alert  = UIAlertController(title: "Get photo from", message: nil, preferredStyle: .ActionSheet)
       
        let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
        alert.addAction(cancelAction)
        
        let libraryAction = UIAlertAction(title: "Photo Library", style: .Default){
          action in
            let imagePickerController = ELCImagePickerController()
            imagePickerController.imagePickerDelegate = self
            
        if Utils.userInterfaceIdiomIsPad {
            self.popController.dismissPopoverAnimated(true)
            self.popController = UIPopoverController(contentViewController: imagePickerController)
            self.popController.presentPopoverFromBarButtonItem(self.navigationItem.rightBarButtonItem!, permittedArrowDirections: .Any, animated: true)
        }else
        {
            self.presentViewController(imagePickerController, animated: true, completion: nil)
        }
        }
        alert.addAction(libraryAction)
        
        //Interner button
        let internetAction = UIAlertAction(title: "Le Interner", style: .Default, handler: {action in
            self.downloadImageAssets()
        })
        alert.addAction(internetAction)
        
        if Utils.userInterfaceIdiomIsPad {
            popController = UIPopoverController(contentViewController: alert)
            popController.presentPopoverFromBarButtonItem(navigationItem.rightBarButtonItem!, permittedArrowDirections: .Any, animated: true)
        }else {
            presentViewController(alert, animated: true, completion: nil)
        }
    
    }
}
// MARK: - Private methods
private extension PhotoCollectionViewController
{
    func contentChangeNotification(notification: NSNotification!)
    {
        collectionView?.reloadData()
        showOrHideNavPrompt()
        NSLog("need reload data");
    }
    
    func showOrHideNavPrompt() {
        
    }
    func downloadImageAssets() {
        PhotoManager.sharedManager.downloadPhotosWithCompletion {  error in
            let message = error?.localizedDescription ?? "the image have finished downloading"
            let alert = UIAlertController(title: "Download Complete", message: message, preferredStyle: .Alert)
            alert.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil))
            self.presentViewController(alert, animated: true, completion: nil)
        }
    }
}





